import re
from django import forms
from django.contrib.auth.models import User

class AccountManagementForm(forms.Form):
	
	email_old = forms.EmailField(widget=forms.HiddenInput)
	email_new = forms.EmailField(label=u'New Email')
	
	def clean_email_new(self):
		#Do not allow multiple users with the same email address, as this will complicate the process of password recovery, etc.
		email_old = self.cleaned_data['email_old']
		email_new = self.cleaned_data['email_new']
		
		if email_old == email_new:
			return email_new
		try:
			u = User.objects.get(email = email_new)
			
		except User.DoesNotExist:
			return email_new
		
		raise forms.ValidationError(u'This email is already associated with a registered user.')


class RegistrationForm(forms.Form):
	username = forms.CharField(label=u'Username', max_length=30)
	email = forms.EmailField(label=u'Email')
	password1 = forms.CharField(
		label=u'Password',
		widget=forms.PasswordInput()
	)
	password2 = forms.CharField(
		label=u'Password (Again)',
		widget=forms.PasswordInput()
	)

	def clean_password2(self):
		if 'password1' in self.cleaned_data:
			password1 = self.cleaned_data['password1']
			password2 = self.cleaned_data['password2']
			if password1 == password2:
				return password2
		raise forms.ValidationError(u'Passwords do not match.')

	def clean_username(self):
		username = self.cleaned_data['username']
		if not re.search(r'^\w+$', username):
			raise forms.ValidationError(u'Username can only contain alphanumeric characters and the underscore.')
		try:
			User.objects.get(username=username)
		except User.DoesNotExist:
			return username
		
		raise forms.ValidationError(u'Username is already taken.')

	def clean_email(self):
		#Do not allow multiple users with the same email address, as this will complicate the process of password recovery, etc.
		email = self.cleaned_data['email']
		try:
			u = User.objects.get(email = email)
		except User.DoesNotExist:
			return email
			
		raise forms.ValidationError(u'This email is already associated with a registered user. Please login or choose a new email address.')

